package de.gameduell.framework.threads 
{
	import flash.events.Event;
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	
	/**
	 * similar to delay action, but this class can run in different target queue's.
	 * This implementation allows to use parallel running multiple queues.
	 * 
	 * @author Ferry Trunschke
	 */
	public class BlockingTimerThread extends ThreadAdapter {

		// timer
		protected var timer:Timer;
		protected var delay:int;
		protected var repeatCount:int = 1;
		
		// callback when timer starts
		// example: show popup
		protected var startCallbackFunction:Function = null;
		protected var startCallbackParameter:Object = null;

		// callback when timer is finished
		// example: hide popup
		protected var finishCallbackFunction:Function = null;
		protected var finishCallbackParameter:Object = null;
		
		public function BlockingTimerThread(delay:int, repeatCount:int = 1, startCallbackFunction:Function = null, startCallbackParameter:Object = null, finishCallbackFunction:Function = null, finishCallbackParameter:Object = null) {
			
			this.delay = delay;
			this.repeatCount = repeatCount;
			
			this.startCallbackFunction = startCallbackFunction;
			this.startCallbackParameter = startCallbackParameter;

			this.finishCallbackFunction = finishCallbackFunction;
			this.finishCallbackParameter = finishCallbackParameter;

			// must be init on start, otherwise calling run() before it was started will stop it instant!
			timer = new Timer(delay, repeatCount);
		}
		
		protected function onTimerComplete(event:Event):void {
			
			// drop timer
			timer.removeEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);	
			timer = null;
		}

		// called from queue manager
		public override function onStartExecution():void {
			
			// start timer
			timer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);	
			timer.start();		

			// invoke callback when supported
			if (startCallbackFunction != null) {
				startCallbackFunction(startCallbackParameter);
			}			
			
		}

		public override function onFinishExecution():void {
			
			// invoke callback when supported
			if (finishCallbackFunction != null) {
				finishCallbackFunction(finishCallbackParameter);
			}	
			
		}
		
		public override function run():Boolean {
			return timer != null;
		}
		
		public override function get isBlockingThread():Boolean {
			return true;
		}

		public override function get description():String {
			return "BlockingTimerThread." + startCallbackFunction + "." + finishCallbackFunction;
		}
		
	}

}